<?php

require_once(APPPATH . 'controllers/frontend/layout.php');

class Customer extends Layout {

    private $_capt = "public/template/backend/images/captcha/";
    private $_customer = "customerinfo";
    public $_format = "Y-m-d H:i:s";

    public function __construct() {
        parent::__construct();
        $this->load->helper('captcha');
    }

    public function login() {
        if ($this->_auth == TRUE)
            redirect("frontend/home", "refresh");
        if ($this->input->post("login")) {
            $post = $this->input->post("data");

            $this->form_validation->set_error_delimiters('<p><label></label><label class="error">', '</label></p>');
            $this->form_validation->set_rules('data[email]', 'Email', 'trim|required|valid_email|xss_clean');
            $this->form_validation->set_rules('data[pass]', 'Mật khẩu', 'trim|required|callback_account_check[' . $post["email"] . ']');
            if ($this->form_validation->run() == TRUE) {
                $user = $this->mcustomers->getCusByEmail($post["email"]);
                $this->session->set_userdata('customer', $user);
                if (($this->input->post('remember')) == 1) {
                    $cookie = array(
                        'name' => $this->_customer,
                        'value' => json_encode($user),
                        'expire' => '86500'
                    );
                    $this->input->set_cookie($cookie);
                }
                redirect("frontend/home");
            }
        }
        $this->_data['title'] = "Đăng nhập";
        $this->_data['temp'] = "frontend/customer/login";
        $this->load->view('frontend/layout/index', $this->_data);
    }

    public function account_check($pass, $email) {
        $count = $this->mcustomers->countCusByEmail($email);
        if ($count == 1) {
            $user = $this->mcustomers->getCusByEmail($email);
            $pass = do_hash($pass, 'md5');
            if ($pass != $user['pass']) {
                $this->form_validation->set_message('account_check', 'Email hoặc Mật khẩu không đúng');
                return FALSE;
            } else
                return TRUE;
        }
        else {
            $this->form_validation->set_message('account_check', 'Email hoặc Mật khẩu không đúng');
            return FALSE;
        }
    }

    public function register() {
        if ($this->_auth == TRUE)
            redirect("frontend/home", "refresh");

        $val = array(
            "word" => "",
            "img_path" => $this->_capt, //đường dẫn để tạo img captcha.
            "img_url" => base_url($this->_capt) . '/', //đã là đường dẫn để hiển thị hình ảnh sau khi tạo xong captcha
            'img_width' => 150,
            'img_height' => 30
        );
        $cap = create_captcha($val);
        $data = array(
            'captcha_time' => $cap['time'],
            'ip_address' => $this->input->ip_address(),
            'word' => $cap['word']
        );

        $query = $this->db->insert_string('captcha', $data);
        $this->db->query($query);
        $this->_data['data']['capt'] = $cap['image'];
        
        $expiration = time() - 600; // clear table        
        $this->db->delete('captcha', array('captcha_time <' => $expiration));

        if ($this->input->post("register")) {
            $post = $this->input->post("data");
             
            $this->form_validation->set_error_delimiters('<label class="error">', '</label>');
            $this->form_validation->set_rules('data[email]', 'Email', 'trim|required|valid_email|is_unique[customers.email]|xss_clean');
            $this->form_validation->set_rules('captcha', 'Mã an toàn', 'trim|required');
            $this->form_validation->set_rules('data[name]', 'Tên', 'trim|required');
            $this->form_validation->set_rules('data[phone]', 'Số điện thoại', 'trim|required|integer|min_length[7]|max_length[13]');
            $this->form_validation->set_rules('data[pass]', 'Mật khẩu', 'trim|required|matches[passconf]');
            $this->form_validation->set_rules('passconf', 'Xác nhận mật khẩu', 'trim|required');
            $this->form_validation->set_rules('data[address]', 'Địa chỉ', 'trim|required');
            if ($this->form_validation->run() == TRUE) {

                // Then see if a captcha exists:
                $sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
                $binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
                $query = $this->db->query($sql, $binds);
                $row = $query->row();

                if ($row->count == 0) {
                    $this->_data['data']['notice'] = "Mã an toàn sai";
                } else {
                    $post['pass'] = do_hash($post['pass'], 'md5');
                    $post['created'] = gmdate($this->_format, time() + 7 * 3600);
                    $this->mcustomers->insert($post);
                    $this->_data['data']['notice'] = "Đăng ký thành công";
                }
            }
        }
        $this->_data['title'] = "Đăng ký";
        $this->_data['temp'] = "frontend/customer/register";
        $this->load->view('frontend/layout/index', $this->_data);
    }

    public function info() {
        if ($this->_auth == FALSE)
            redirect("frontend/home", "refresh");
        $u = $this->session->userdata('customer');

        if ($this->input->post("info")) {
            $post = $this->input->post("data");

            $this->form_validation->set_error_delimiters('<label class="error">', '</label>');
            $this->form_validation->set_rules('data[name]', 'Tên', 'trim|required');
            $this->form_validation->set_rules('data[phone]', 'Số điện thoại', 'trim|required|integer|min_length[7]|max_length[13]');
            $this->form_validation->set_rules('data[address]', 'Địa chỉ', 'trim|required');
            if ($this->form_validation->run('info') == TRUE) {
                $this->mcustomers->update($u['id'], $post);
                $this->_data['data']['notice1'] = "Thay đổi thành công";
            }
        } elseif ($this->input->post("change-pass")) {
            $post = $this->input->post("data");
            $this->form_validation->set_error_delimiters('<label class="error">', '</label>');
            $this->form_validation->set_rules('oldpass', 'Mật khẩu cũ', 'trim|required|callback_info_pass[' . $u["email"] . ']');
            $this->form_validation->set_rules('data[pass]', 'Mật khẩu mới', 'trim|required|matches[passconf]');
            $this->form_validation->set_rules('passconf', 'Xác nhận mật khẩu', 'trim|required');
            if ($this->form_validation->run('change-pass') == TRUE) {
                $post['pass'] = do_hash($post['pass'], 'md5');
                $this->mcustomers->update($u['id'], $post);
                $user = $this->mcustomers->getCusByEmail($u["email"]);
                $this->session->set_userdata('customer', $user);
                if (isset($_COOKIE[$this->_customer]) && !empty($_COOKIE[$this->_customer])) {
                    $cookie = array(
                        'name' => $this->_customer,
                        'value' => json_encode($user),
                        'expire' => '86500'
                    );
                    $this->input->set_cookie($cookie);
                }
                $this->myclass->js_redirect("Đổi mật khẩu thành công", base_url("frontend/customer/info"));
            }
        }

        $this->_data['data']['order'] = $this->morders->getByCusId($u['id']);
        $this->_data['data']['cus'] = $this->mcustomers->fetchOne($u['id']);
        $this->_data['title'] = "Thông tin khách hàng";
        $this->_data['temp'] = "frontend/customer/info";
        $this->load->view('frontend/layout/index', $this->_data);
    }

    public function info_pass($pass, $email) {
        $user = $this->mcustomers->getCusByEmail($email);
        $pass = do_hash($pass, 'md5');
        if ($pass != $user['pass']) {
            $this->form_validation->set_message('info_pass', 'Mật khẩu không đúng');
            return FALSE;
        } else
            return TRUE;
    }

    public function logout() {
        if ($this->_auth == FALSE)
            redirect("frontend/home", "refresh");
        $this->session->unset_userdata('customer');
        if (isset($_COOKIE[$this->_customer]) && !empty($_COOKIE[$this->_customer]))
            delete_cookie($this->_customer);
        redirect("frontend/home");
    }

    public function forget() {
        if ($this->_auth == TRUE)
            redirect("frontend/home", "refresh");
        if ($this->input->post("forget")) {
            $post = $this->input->post("data");

            $this->form_validation->set_error_delimiters('<p><label></label><label class="error">', '</label></p>');
            $this->form_validation->set_rules('data[email]', 'Email', 'trim|required|valid_email|xss_clean|callback_email_check');

            if ($this->form_validation->run() == TRUE) {
                $user = $this->mcustomers->getCusByEmail($post["email"]);
                $pass = random_string('alpha', 5);
                $post['pass'] = do_hash($pass, 'md5');
                $this->mcustomers->update($user['id'], $post);
                $this->myclass->sendmail(array(
                    'name' => 'Full house',
                    'to' => $post['email'],
                    'subject' => 'Reset mật khẩu cho: ' . $post['email'],
                    'message' => 'Email: ' . $post['email'] . '<br/> Pass: ' . $pass
                ));
                $this->myclass->js_redirect("Gửi email thành công, mời check email", base_url("frontend/customer/login"));
            }
        }
        $this->_data['title'] = "Quên mật khẩu";
        $this->_data['temp'] = "frontend/customer/forget";
        $this->load->view('frontend/layout/index', $this->_data);
    }

    public function email_check($email) {
        $count = $this->mcustomers->countCusByEmail($email);
        if ($count == 0) {
            $this->form_validation->set_message('email_check', 'Email không tồn tại');
            return FALSE;
        } else
            return TRUE;
    }

}
